#include "StdAfx.h"
#include "FileIOMag.h"

#include "LogWrapper.h"

CFileIOMag::CFileIOMag(void)
{
	m_hModule = NULL;
	m_lpOpenDRFile  = NULL;
	m_lpCloseDRFile = NULL;	
}

CFileIOMag::~CFileIOMag(void)
{
	this->Destroy();
}

bool CFileIOMag::Initialize()
{

#ifdef _WIN64
	#ifdef DEBUG
		 m_hModule = LoadLibrary(L"CTFileIO64.dll");
	#else
		 m_hModule = LoadLibrary(L"CTFileIO64.dll");
	#endif
#endif

	DWORD dwError = GetLastError();
 	if (dwError != 0 && !m_hModule)
	{
		CSingleton<CLogWrapper>::Instance()->Log(ERROR_LOG, L"load CTFileIO failed. Error code is %d.\n", dwError);
		return false;
	}
	m_lpOpenDRFile = (LPOpenDRFile)GetProcAddress(m_hModule, "OpenDRFile");
	dwError = GetLastError();
	if (!m_lpOpenDRFile)
	{
		CSingleton<CLogWrapper>::Instance()->Log(ERROR_LOG, L"get OpenDRFile interface failed. Error code is %d.\n", dwError);
		return false;
	}
	m_lpCloseDRFile= (LPCloseDRFile)GetProcAddress(m_hModule, "CloseDRFile");
	dwError = GetLastError();
	if (!m_lpCloseDRFile)
	{
		CSingleton<CLogWrapper>::Instance()->Log(ERROR_LOG, L"get CloseDRFile interface failed. Error code is %d.\n", dwError);
		return false;
	}

	m_lpOpenImgFile = (LPOpenImgFile)GetProcAddress(m_hModule, "OpenImgFile");
	dwError = GetLastError();
	if (!m_lpOpenImgFile)
	{
		CSingleton<CLogWrapper>::Instance()->Log(ERROR_LOG, L"get OpenImgFile interface failed. Error code is %d.\n", dwError);
		return false;
	}
	m_lpCloseImgFile= (LPCloseImgFile)GetProcAddress(m_hModule, "CloseImgFile");
	dwError = GetLastError();
	if (!m_lpCloseImgFile)
	{
		CSingleton<CLogWrapper>::Instance()->Log(ERROR_LOG, L"get CloseImgFile interface failed. Error code is %d.\n", dwError);
		return false;
	}
	return true;
}

void CFileIOMag::Destroy()
{
	if (m_hModule)
	{
		FreeLibrary(m_hModule);
		m_hModule = NULL;
		m_lpOpenDRFile = NULL;
		m_lpCloseDRFile= NULL;
	}
}

IDRFileIO* CFileIOMag::OpenDRFile(const wchar_t szFileName[256], OpenMode openMode )
{
	if (m_lpOpenDRFile)
	{
		return (*m_lpOpenDRFile)(szFileName, openMode);
	}
	else
	{
		return NULL;
	}
}

FileIOStatus CFileIOMag::CloseDRFile( IDRFileIO* pFileIO )
{
	if (m_lpCloseDRFile)
	{
		(*m_lpCloseDRFile)(pFileIO);
		return fileIOStsNoErr;
	}
	else
	{
		return fileIOLackDataErr;
	}
}

IImgFileIO*	 CFileIOMag::OpenImgFile(wchar_t szFileName[256], OpenMode openMode)
{
	if (m_lpOpenImgFile)
	{
		return (*m_lpOpenImgFile)(szFileName, openMode);
	}
	else
	{
		return NULL;
	}
}
FileIOStatus CFileIOMag::CloseImgFile(IImgFileIO* pFileIO)
{
	if (m_lpCloseImgFile)
	{
		(*m_lpCloseImgFile)(pFileIO);
		return fileIOStsNoErr;
	}
	else
	{
		return fileIOLackDataErr;
	}
}